package top.zhangjianyong.tools.reptile;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import top.zhangjianyong.tools.utils.JDBCUtil;
import top.zhangjianyong.tools.utils.UUIDUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.sql.SQLException;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/22 8:46 AM
 */
public class DownloadUtil {

    private final static String DIR = "/Users/zhangjianyong/img";

    /**
     * 下载图片并保存数据库
     *
     * @param imgUrl 图片地址
     * @param url    来源地址
     * @throws IOException
     */
    public static void downloadImg(String imgUrl, String url) throws IOException, SQLException {
        System.out.println("下载图片：" + imgUrl);
        HttpRequest get = HttpUtil.createGet(imgUrl);
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 301) {
            System.out.println("图片重定向");
            String location = execute.header("Location");
            imgUrl = UrlUtil.getUrl(location, imgUrl);
            downloadImg(imgUrl, url);
            return;
        }
        String contentType = execute.header("Content-Type");
        String ext = "png";

        if (contentType != null && contentType.contains("/")) {
            ext = contentType.split("/")[1];
        }
        ImgInfo imgInfo = getImgSize(execute.bodyStream());

        String fileName = fileName(imgUrl, ext);
        int length = fileName.length();
        if (length > 64) {
            fileName = fileName.substring(length - 64);
        }
        String filePath = DIR + File.separator + imgInfo.size + File.separator + fileName;
        execute.writeBody(filePath);
        /*保存到数据库*/
        JDBCUtil.update("INSERT into reptile_img(url,img_url,img_size,width,height,name,path,type) VALUES(?,?,?,?,?,?,?,?)",
                url, imgUrl, execute.contentLength() / 1024, imgInfo.width, imgInfo.height,
                fileName, filePath, imgInfo.size);
    }

    public static void downloadVideo(String videoUrl, String url) throws UnsupportedEncodingException, SQLException {
        System.out.println("下载视频：" + videoUrl);
        HttpRequest get = HttpUtil.createGet(videoUrl);
        HttpResponse execute = get.execute();
        String contentType = execute.header("Content-Type");
        String ext = "mp4";
        if (contentType.contains("/")) {
            ext = contentType.split("/")[1];
        }

        String fileName = fileName(videoUrl, ext);
        int length = fileName.length();
        if (length > 64) {
            fileName = fileName.substring(length - 64);
        }
        String filePath = DIR + File.separator + "video" + File.separator + fileName;
        execute.writeBody(filePath);
        /*保存到数据库*/
        JDBCUtil.update("INSERT into reptile_img(url,img_url,img_size,width,height,name,path,type) VALUES(?,?,?,?,?,?,?,?)",
                url, videoUrl, execute.contentLength() / 1024, 0, 0,
                fileName, filePath, "video");
    }

    public static class ImgInfo {

        public int width;
        public int height;
        public String size;

        public ImgInfo(int width, int height) {

            this.width = width;
            this.height = height;
            int size = width * height;
            this.size = "small";
            if (size <= 0) {
                this.size = "default";
            } else if (size <= (300 * 300)) {
                this.size = "small";
            } else if (size <= (1200 * 700)) {
                this.size = "median";
            } else if (size <= (2000 * 2000)) {
                this.size = "big";
            } else {
                this.size = "large";
            }

        }
    }

    public static ImgInfo getImgSize(InputStream inputStream) throws IOException {
        try {
            BufferedImage img = ImageIO.read(inputStream);
            if (img == null) {
                return new ImgInfo(0, 0);
            }
            return new ImgInfo(img.getWidth(), img.getHeight());
        } catch (Exception e) {
            e.getMessage();
            return new ImgInfo(0, 0);
        }

    }

    /**
     * 获取图片名字
     *
     * @param url
     * @return
     */
    public static String fileName(String url, String ext) throws UnsupportedEncodingException {
        String imgUrl = url;
        url = URLDecoder.decode(url, Charset.defaultCharset().name());
        if (url.contains("?")) {
            int i = url.indexOf("?");
            url = url.substring(0, i);
        }
        if (url.contains("&")) {
            int i = url.indexOf("&");
            url = url.substring(0, i);
        }

        String[] split = url.split("/");
        String origin = split[split.length - 1];
        if (origin.contains(".")) {
            int i = origin.lastIndexOf(".");
            String name = origin.substring(0, i);
            ext = origin.substring(i + 1);
            return name + "_" + UrlUtil.host(imgUrl) + "_" + UUIDUtil.randomFileName(ext);
        } else {
            return origin + "_" + UrlUtil.host(imgUrl) + "_" + UUIDUtil.randomFileName(ext);
        }

    }

    public static void main(String[] args) throws SQLException, IOException {
        String url =
                "https://www.baidu.com/s?wd=%E6%96%B0%E7%96%86%E6%B0%91%E6%AD%8C&tn=baidutop10&rsv_idx=2&usm=1&ie=utf-8&rsv_pq=e898c5ac000008a2&oq=%E7%8E%9B%E4%BE%9D%E6%8B%89%E4%BC%B4%E5%A5%8F%E6%9B%B2&rsv_t=e9e8NBzzCTGP6pGM8600Pq%2BMCx9bbbd32wrwnK1u8dq42otpcR0WnzKJqEApzTtKLw&rsv_cq=&rsv_dl=0_right_recommends_merge_21102&euri=98d19bedb8c949949bcb0df1bd69265b";
        String imgUrl =
                "https://gimg3.baidu.com/yule/src=http%3A%2F%2Fgips2.baidu.com%2Fit%2Fu%3D3712542103%2C546953087%26fm%3D3007%26app%3D3007%26f%3DJPEG%3Fw%3D300%26h%3D300&refer=http%3A%2F%2Fwww.baidu.com&app=2019&size=w931&n=0&g=0n&q=75&fmt=auto?sec=1679763600&t=3868d4a354ac3662cc8e4dcc12240689";
        downloadImg(imgUrl, url);
    }
}
